package org.friut.server;

import java.io.BufferedInputStream;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.ByteArrayBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public enum HttpHandler {
	
	INSTANCE;
	
	private static Logger LOG = LoggerFactory.getLogger(HttpHandler.class);
	
	public String get(String url) {
		HttpClient httpclient = new DefaultHttpClient();
		
		StringBuilder sb = new StringBuilder();
		try {
			HttpGet httpget = new HttpGet(url);
			HttpResponse response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				InputStream is = response.getEntity().getContent();
				BufferedInputStream bis = new BufferedInputStream(is);
				ByteArrayBuffer baf = new ByteArrayBuffer(20);
				int current = 0;
				while ((current = bis.read()) != -1) {
					baf.append((byte) current);
				}
				sb.append(new String(baf.toByteArray(), "utf-8"));
			}
			httpget.abort();
		} catch (Exception e) {
			LOG.error("Http send error.", e);
		} finally {
			httpclient.getConnectionManager().shutdown();
		}
		return sb.toString();
	}
}
